package com.example.ymm.modules1.service.impl.hl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.TableList;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.yw.*;
import com.example.ymm.modules1.entity.ms.DDepartment;
import com.example.ymm.modules1.entity.ms.DEmployee;
import com.example.ymm.modules1.entity.my.user.DbApprovalLog;
import com.example.ymm.modules1.mapper.hl.YwMoneyAffirmLogMapper;
import com.example.ymm.modules1.query.hl.*;
import com.example.ymm.modules1.service.dto.heng.*;
import com.example.ymm.modules1.service.dto.ms.CountMoneyAffirmDto;
import com.example.ymm.modules1.service.dto.ms.CountMoneyUserDto;
import com.example.ymm.modules1.service.dto.ms.MsMoneyAffirmDto;
import com.example.ymm.modules1.service.dto.ms.MsMoneyAffirmOrderDto;
import com.example.ymm.modules1.service.hl.*;
import com.example.ymm.modules1.service.ms.DDepartmentService;
import com.example.ymm.modules1.service.ms.DEmployeeService;
import com.example.ymm.modules1.service.user.DbApprovalLogService;
import com.example.ymm.util.QueryHelpPlus;
import com.example.ymm.util.UtilValidate;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@DS("slave2")
public class YwMoneyAffirmLogServiceImpl extends BaseServiceImpl<YwMoneyAffirmLogMapper, YwMoneyAffirmLog>
        implements YwMoneyAffirmLogService {

    @Autowired
    YwAccountOutoRateService ywAccountOutoRateService;
    @Autowired
    YwDeptMainRateService ywDeptMainRateService;
    @Autowired
    YwDeptNextRateService ywDeptNextRateService;

    @Autowired
    YwMoneyChangeLogService ywMoneyChangeLogService;
    @Autowired
    DDepartmentService dDepartmentService;
    @Autowired
    YwUserService ywUserService;
    @Autowired
    DEmployeeService employeeService;
    @Autowired
    YwExcludeFapiaoItemService ywExcludeFapiaoItemService;
    @Autowired
    DbApprovalLogService dbApprovalLogService;

    List<YwAccountOutoRate> rates = null;//业务员固定比例
    List<YwDeptMainRate> mainRates = null;//业务部门主要抽成
    List<YwDeptNextRate> nextRates = null;//时俱佳其他客户抽成
    YwDeptMainRate dknMainRat=null;//迪卡侬新老订单比例
    @Autowired
    private YwDeptService ywDeptService;
    @Autowired
    private YwCommissionConfigService ywCommissionConfigService;


    @PostConstruct
    public void initFn() {
        YwAccountOutoRateQueryCriteria c1 = new YwAccountOutoRateQueryCriteria();
        c1.setType(0);
        this.rates = ywAccountOutoRateService.queryAll(c1);
        this.mainRates = ywDeptMainRateService.queryAll(null);
        this.nextRates = ywDeptNextRateService.queryAll(null);
        for(YwDeptMainRate mainRate:mainRates){
            if("迪卡侬营销部".equals(mainRate.getDeptName())&&UtilValidate.isNotEmpty(mainRate.getNewCustomerRate())){
                dknMainRat=mainRate;
            }
        }
    }

    @Override
    public TableList<MsMoneyAffirmDto> list(YwMoneyAffirmLogQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        criteria.setOrderNoIsNull("1");
        List<MsMoneyAffirmDto> arrs = msMoneyAffirmList(criteria);
        PageInfo<MsMoneyAffirmDto> pageInfo = new PageInfo<>(arrs);
        TableList<MsMoneyAffirmDto> tableList = new TableList(pageInfo);
        return tableList;
    }

    public List<YwMoneyAffirmLog> queryAll(YwMoneyAffirmLogQueryCriteria criteria) {
        QueryWrapper predicate = QueryHelpPlus.getPredicate(YwMoneyAffirmLog.class, criteria);
        predicate.orderByDesc("create_time");
        List<YwMoneyAffirmLog> result = baseMapper.selectList(predicate);
        return result;
    }


    @Override
    public YwMoneyAffirmLog getByOrderNo(String orderNo) {
        YwMoneyAffirmLogQueryCriteria criteria=new YwMoneyAffirmLogQueryCriteria();
        criteria.setOrderNo(orderNo);
        YwMoneyAffirmLog affirmLog=null;
        List<YwMoneyAffirmLog> ywMoneyAffirmLogs = queryAll(criteria);
        if(ywMoneyAffirmLogs.size()>0){
            affirmLog=ywMoneyAffirmLogs.get(0);
        }
        return affirmLog;
    }

    @Override
    public CountMoneyAffirmDto countMoneyAffirm(YwMoneyAffirmLogQueryCriteria criteria) {
        CountMoneyAffirmDto countMoneyAffirmDto = new CountMoneyAffirmDto();
        criteria.setOrderNoIsNull("1");
        List<MsMoneyAffirmDto> msMoneyAffirmDtos = msMoneyAffirmList(criteria);

        synchronized (this) {
            BigDecimal totalAllPrice=BigDecimal.ZERO;// 金额 金额 乘于汇率
            BigDecimal orderCommissionPrice=BigDecimal.ZERO;// 订单抽成金额
            BigDecimal receiverUserPrice=BigDecimal.ZERO;// 接单人抽成金额
            BigDecimal merchandiserUserPrice=BigDecimal.ZERO;// 跟单人抽成金额
            BigDecimal manageUserPrice=BigDecimal.ZERO;// 经理抽成金额
            BigDecimal xiangMuGroupPrice=BigDecimal.ZERO; // 项目组抽成金额
            BigDecimal jiJingPrice=BigDecimal.ZERO;//基金金额
            for(MsMoneyAffirmDto dto: msMoneyAffirmDtos){
                if(UtilValidate.isNotEmpty(dto.getTotalAllPrice())){
                    totalAllPrice=totalAllPrice.add(dto.getTotalAllPrice());
                }
                if(UtilValidate.isNotEmpty(dto.getOrderCommissionPrice0())){
                    orderCommissionPrice=orderCommissionPrice.add(dto.getOrderCommissionPrice0());
                }
                if(UtilValidate.isNotEmpty(dto.getReceiverUserPrice0())){
                    receiverUserPrice=receiverUserPrice.add(dto.getReceiverUserPrice0());
                }
                if(UtilValidate.isNotEmpty(dto.getMerchandiserUserPrice0())){
                    merchandiserUserPrice=merchandiserUserPrice.add(dto.getMerchandiserUserPrice0());
                }
                if(UtilValidate.isNotEmpty(dto.getManageUserPrice0())){
                    manageUserPrice=manageUserPrice.add(dto.getManageUserPrice0());
                }
                if(UtilValidate.isNotEmpty(dto.getXiangMuGroupPrice0())){
                    xiangMuGroupPrice=xiangMuGroupPrice.add(dto.getXiangMuGroupPrice0());
                }
                if(UtilValidate.isNotEmpty(dto.getJiJingPrice0())){
                    jiJingPrice=jiJingPrice.add(dto.getJiJingPrice0());
                }
            }
            countMoneyAffirmDto.setTotalAllPrice(totalAllPrice);
            countMoneyAffirmDto.setOrderCommissionPrice(orderCommissionPrice);
            countMoneyAffirmDto.setReceiverUserPrice(receiverUserPrice);
            countMoneyAffirmDto.setMerchandiserUserPrice(merchandiserUserPrice);
            countMoneyAffirmDto.setManageUserPrice(manageUserPrice);
            countMoneyAffirmDto.setXiangMuGroupPrice(xiangMuGroupPrice);
            countMoneyAffirmDto.setJiJingPrice(jiJingPrice);
        }



        return countMoneyAffirmDto;
    }

    @Override
    public void removeByApproveNo(String approveNo) {

//        LambdaQueryWrapper<YwMoneyAffirmLog> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(YwMoneyAffirmLog::getApproveNo, approveNo);
        YwMoneyAffirmLogQueryCriteria criteria=new YwMoneyAffirmLogQueryCriteria();
        criteria.setApproveNo(approveNo);
        List<YwMoneyAffirmLog> logs = queryAll(criteria);
        for(YwMoneyAffirmLog alog:logs){
            alog.setOrderNo(alog.getOrderNo()+"已撤销");
            saveOrUpdate(alog);

        }
//        remove(queryWrapper);

    }

    @Override
    public List<YwMoneyAffirmLog> listByApproveNo(String approveNo) {
        YwMoneyAffirmLogQueryCriteria criteria = new YwMoneyAffirmLogQueryCriteria();
        criteria.setApproveNo(approveNo);
        List<YwMoneyAffirmLog> queryAll = queryAll(criteria);
        List<String> orderNos=new ArrayList<>();
        List<String> skuNoIn=new ArrayList<>();
        for(YwMoneyAffirmLog alog:queryAll){
            String orderNo = alog.getOrderNo();
            if(UtilValidate.isNotEmpty(orderNo)){
                if(orderNo.contains("已驳回")||orderNo.contains("已撤销")){
                    orderNo=orderNo.replaceAll("已驳回","").replaceAll("已撤销","");
                }
            }
            orderNos.add(orderNo);
        }
        if(UtilValidate.isNotEmpty(orderNos)){
            YwExcludeFapiaoItemQueryCriteria c2=new YwExcludeFapiaoItemQueryCriteria();
            c2.setOrderNoIn(orderNos);
            List<String> os = ywExcludeFapiaoItemService.getOrderNo(c2);

            for(YwMoneyAffirmLog alog:queryAll){
                for(String o:os){
                    if(alog.getOrderNo().equals(o)){
                        alog.setIsExclude(1);
                    }
                }


            }
        }
        List<String> yushouNoIn=new ArrayList<>();
        for(YwMoneyAffirmLog alog:queryAll){
            if(UtilValidate.isNotEmpty(alog.getType())){
                if("收款确认".equals(alog.getType())){
                    skuNoIn.add(alog.getOrderNo());
                }else{
                    yushouNoIn.add(alog.getOrderNo());
                }
            }
        }

        List<YuShouItem>  dataList=new ArrayList<>();

        if(UtilValidate.isNotEmpty(skuNoIn)){
            FaPiaoItemQueryCriteria criteria1=new FaPiaoItemQueryCriteria();
            criteria1.setSkqrNoIn(skuNoIn);
            List<FaPiaoItem> faPiaoItems = shouKuanQueRenItemList(criteria1);
            if(UtilValidate.isNotEmpty(faPiaoItems)){
                dataList.addAll(faPiaoItems);
            }
        }
        if(UtilValidate.isNotEmpty(orderNos)){
            FaPiaoItemQueryCriteria criteria2=new FaPiaoItemQueryCriteria();
            criteria2.setSkqrNoIn(orderNos);

            List<YuShouItem> faPiaoItems = yushoukuanItemList(criteria2);
            if(UtilValidate.isNotEmpty(faPiaoItems)){
                dataList.addAll(faPiaoItems);
            }
        }

        if(UtilValidate.isNotEmpty(dataList)){


            for (YwMoneyAffirmLog dto:queryAll){
                List<YuShouItem> children=new ArrayList<>();
                for (YuShouItem item : dataList){
                    if(dto.getOrderNo().startsWith(item.getSkqrNo())){
                        children.add(item);
                    }
                }
                if(UtilValidate.isNotEmpty(children)){
                    Map<String,String> saleOrderMap=new HashMap<>();//销售订单号存储map

                    for (YuShouItem item : children){
                         if(UtilValidate.isNotEmpty(item.getXiaoShouDingDanTID())){
                            saleOrderMap.put(item.getXiaoShouDingDanTID(),item.getXiaoShouDingDanTID());
                        }else if(UtilValidate.isNotEmpty(item.getPiCiHao())){
                            saleOrderMap.put(item.getPiCiHao(),item.getPiCiHao());
                        }
//                        saleOrderMap.put(item.getXiaoShouDingDanTID(),item.getXiaoShouDingDanTID());
                    }

                }
                dto.setChildren(children);

                if(UtilValidate.isNotEmpty(children)){
                    Map<String,String> saleOrderMap=new HashMap<>();//销售订单号存储map
                    Map<String,String> faBiaoMap=new HashMap<>();//发票号存储map

                    for (YuShouItem item : children){
//                        if(UtilValidate.isNotEmpty(item.getPiCiHao())){
//                            saleOrderMap.put(item.getPiCiHao(),item.getPiCiHao());
//                        }else if(UtilValidate.isNotEmpty(item.getXiaoShouDingDanTID())){
//                            saleOrderMap.put(item.getXiaoShouDingDanTID(),item.getXiaoShouDingDanTID());
//                        }
//                        saleOrderMap.put(item.getXiaoShouDingDanTID(),item.getXiaoShouDingDanTID());
                        if(UtilValidate.isNotEmpty(item.getXiaoShouDingDanTID())){
                            saleOrderMap.put(item.getXiaoShouDingDanTID(),item.getXiaoShouDingDanTID());
                        }else if(UtilValidate.isNotEmpty(item.getPiCiHao())){
                            saleOrderMap.put(item.getPiCiHao(),item.getPiCiHao());
                        }
                        if(UtilValidate.isNotEmpty(item.getZhuTID())){
                            faBiaoMap.put(item.getZhuTID(),item.getZhuTID());
                        }

                    }
//                List<String> orderNoList=new ArrayList<>();
                    String orderNoStrs=String.join(",",saleOrderMap.keySet());
                    dto.setPiCiHao(orderNoStrs);
                    //发票号
                    if(faBiaoMap.size()>0){
                        String faBiaoStrs=String.join(",",faBiaoMap.keySet());
                        dto.setFaPiaoHao(faBiaoStrs);
                    }
                }
            }
        }
        return queryAll;
    }

    @Override
    public List<MsMoneyAffirmDto> msMoneyAffirmList(YwMoneyAffirmLogQueryCriteria criteria) {
//        if(UtilValidate.isNotEmpty(criteria.getDateArr())){
//            List<String> dateArr = criteria.getDateArr();
//            String startTime= dateArr.get(0)+" 00:00:00";
//            String endTime= dateArr.get(1)+" 24:00:00";
//            criteria.setStartTime(startTime);
//            criteria.setEndTime(endTime);
//        }
        if(UtilValidate.isEmpty(criteria.getOrderNoIsNull())&&UtilValidate.isEmpty(criteria.getOrderNoIn())){
            throw new YmException("查询异常！");
        }
        if(UtilValidate.isEmpty(criteria.getState0())){
            criteria.setState0(9999);
        }
        List<MsMoneyAffirmDto> arrs = baseMapper.msMoneyAffirmList(criteria);
        List<String> skuNoIn=new ArrayList<>();
        List<String> yushouNoIn=new ArrayList<>();

        for (MsMoneyAffirmDto msMoneyAffirmDto : arrs) {
            BigDecimal orderCommissionRate0=null;
            BigDecimal orderCommissionPrice0=null;


            /**
             * 部门比例 --开始
             */
            boolean isShiJuJiaFixed=false;//是否为时俱佳固定客户
            for (YwDeptMainRate mainRate : mainRates) {

                if(mainRate.getDeptId().equals(msMoneyAffirmDto.getSalesmanDeptId0())){
                    /**
                     * 客户类型 1新老客户 2固定客户
                     */

                    if(mainRate.getType()==2){
                        if(mainRate.getFixedCustomerNo().equals(msMoneyAffirmDto.getCustomerNo())){
                            orderCommissionRate0=mainRate.getFixedCustomerRate();
                            isShiJuJiaFixed=true;
                        }
                    }
                }
            }

            for (YwDeptMainRate mainRate : mainRates) {
                if(msMoneyAffirmDto.getSalesmanDeptId0().equals(mainRate.getDeptId())){
                    /**
                     * 客户类型 1新老客户 2固定客户
                     */

                    if(!isShiJuJiaFixed&&mainRate.getType()==1){
                        //新客户首三单
                        if(msMoneyAffirmDto.getXinKeHuShouSanDan()==1){
                            orderCommissionRate0=mainRate.getNewCustomerRate();
                        }else{
                            /**
                             * 老客户订单类型: 1 不分成品和配件 2 区分成品和配件 3 区分国内外销售
                             */
                            switch (mainRate.getOldCustomerType()){
                                case 1: //老客户 不分成品和配件抽成比例
                                    if(msMoneyAffirmDto.getXinKeHuShouSanDan()==1){
                                        orderCommissionRate0=mainRate.getNewCustomerRate();
                                    }else {
                                        orderCommissionRate0=mainRate.getOldCustomerOriginalRate();
                                    }
                                    break;
                                case 2://区分成品和配件
                                    if(msMoneyAffirmDto.getPeiJianDingDan()==1){
                                        orderCommissionRate0=mainRate.getOldCustomerPartRate();
                                    }else{
                                        orderCommissionRate0=mainRate.getOldCustomerFinishedRate();//老客户成品比例
                                    }
                                    break;
                                case 3:
                                    //国内外销售

                                    if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getDiQuNo())){
                                        String diQuNoNo = msMoneyAffirmDto.getDiQuNo().substring(6, msMoneyAffirmDto.getDiQuNo().length());
                                        Integer diQuNum = Integer.valueOf(diQuNoNo);
                                        //DQGL0001 到 DQGL0033 是国内
                                        if(diQuNum>33){//国外
                                            orderCommissionRate0=mainRate.getOldCustomerForeignRate();//国外销售
                                        }else{//国内
                                            orderCommissionRate0=mainRate.getOldCustomerHomeRate();//国内销售
                                        }
                                    }

//                                if("中国大陆".equals(msMoneyAffirmDto.getSuoShuQuYu())){
//                                    orderCommissionRate0=mainRate.getOldCustomerHomeRate();//国内销售
//                                }else if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getSuoShuQuYu())&&
//                                        !"中国大陆".equals(msMoneyAffirmDto.getSuoShuQuYu())){
//                                    orderCommissionRate0=mainRate.getOldCustomerForeignRate();//国外销售
//                                }
//                                break;
                            }
                        }

                    }
                }
            }
            if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getOrderCommissionRate1())){
                orderCommissionRate0=msMoneyAffirmDto.getOrderCommissionRate1();
            }


            /**
             * 部门比例 --结束
             */

            //--计算订单抽成金额
            if(UtilValidate.isNotEmpty(orderCommissionRate0)){
                if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getTotalFapiaoItemPrice())){
                    msMoneyAffirmDto.setTotalAllPrice(msMoneyAffirmDto.getTotalFapiaoItemPrice());
                }
                orderCommissionPrice0 = msMoneyAffirmDto.getTotalAllPrice().multiply(orderCommissionRate0).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);

                //计算接单人 跟单人金额
                BigDecimal business = orderCommissionPrice0.multiply(msMoneyAffirmDto.getBusinessGroupRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getReceiverUserName0())){
                    int i = msMoneyAffirmDto.getReceiverUserRate0().compareTo(BigDecimal.ZERO);
                    if(i>0){
                        BigDecimal receiverUserPrice = business.multiply(msMoneyAffirmDto.getReceiverUserRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        msMoneyAffirmDto.setReceiverUserPrice0(receiverUserPrice);
                    }else if(UtilValidate.isEmpty(msMoneyAffirmDto.getMerchandiserUserName0())){

                        //没有跟单人
                        msMoneyAffirmDto.setReceiverUserRate0(new BigDecimal(100));
                        msMoneyAffirmDto.setReceiverUserPrice0(business);

                    }
                } else{
                    //没有接单人
                    msMoneyAffirmDto.setReceiverUserNo0(msMoneyAffirmDto.getSalesmanNo0());
                    msMoneyAffirmDto.setReceiverUserName0(msMoneyAffirmDto.getSalesmanName0());
                    if(UtilValidate.isEmpty(msMoneyAffirmDto.getReceiverUserRate0())||msMoneyAffirmDto.getReceiverUserRate0().compareTo(BigDecimal.ZERO)==0){
                        msMoneyAffirmDto.setReceiverUserRate0(new BigDecimal(100));
                        msMoneyAffirmDto.setReceiverUserPrice0(business);
                    }else if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getReceiverUserRate0())||msMoneyAffirmDto.getReceiverUserRate0().compareTo(BigDecimal.ZERO)>0){
                        BigDecimal receiverUserPrice = business.multiply(msMoneyAffirmDto.getReceiverUserRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        msMoneyAffirmDto.setReceiverUserPrice0(receiverUserPrice);
                    }

                }

                //计算跟单人
                if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getMerchandiserUserName0())){
                    if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getMerchandiserUserRate0())){
                        BigDecimal merchandiserUserPrice = business.multiply(msMoneyAffirmDto.getMerchandiserUserRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        msMoneyAffirmDto.setMerchandiserUserPrice0(merchandiserUserPrice);
                    }
                }
                //项目经理
                if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getManageUserRate0())){
                    BigDecimal managerPrice =null;
                    // 这种计算方式 包含了 是否额外的情况
                    if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getManageUserExtra())){
                        if(msMoneyAffirmDto.getSalesmanDeptName0().equals("钟营销部")){
                            msMoneyAffirmDto.setManageUserName0(null);
                            msMoneyAffirmDto.setManageUserNo0(null);
                            managerPrice =null;
                        }else{
                            managerPrice = msMoneyAffirmDto.getTotalAllPrice().multiply(msMoneyAffirmDto.getManageUserRate0()).divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP);
                        }
                    }else{
                        managerPrice = orderCommissionPrice0.multiply(msMoneyAffirmDto.getManageUserRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    }
                    msMoneyAffirmDto.setManageUserPrice0(managerPrice);
                }
                //项目组
                if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getXiangMuGroupName0())){
                    BigDecimal xiangmuGroupPrice = orderCommissionPrice0.multiply(msMoneyAffirmDto.getXiangmuGroupRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    msMoneyAffirmDto.setXiangMuGroupPrice0(xiangmuGroupPrice);
                }
                //基金
                if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getJiJingName0())){
                    BigDecimal JiJingPrice = orderCommissionPrice0.multiply(msMoneyAffirmDto.getJiJingRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    msMoneyAffirmDto.setJiJingPrice0(JiJingPrice);
                }

                msMoneyAffirmDto.setOrderCommissionPrice0(orderCommissionPrice0);
                msMoneyAffirmDto.setOrderCommissionRate0(orderCommissionRate0);
            }


            //没有接单人
            if(UtilValidate.isEmpty(msMoneyAffirmDto.getReceiverUserNo0())){
                msMoneyAffirmDto.setReceiverUserNo0(msMoneyAffirmDto.getSalesmanNo0());
                msMoneyAffirmDto.setReceiverUserName0(msMoneyAffirmDto.getSalesmanName0());
            }

            //节点跟单比例设置
            for (YwAccountOutoRate rate : rates) {

                /**
                 * 这边开始 优先按照 固定比例的配置开始计算
                 */
                    if (UtilValidate.isNotEmpty(rate.getReceiverUserRate())
                            && UtilValidate.isNotEmpty(msMoneyAffirmDto.getReceiverUserName0()) &&
                            msMoneyAffirmDto.getReceiverUserName0().equals(rate.getReceiverUserName())
                            && UtilValidate.isEmpty(msMoneyAffirmDto.getAccountOutoRateId())
                    ) {
                        //钟部 许建晶 会走这个逻辑
                        if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getOrderCommissionPrice0())){
                            // 接单人抽成

                            BigDecimal receiverUserRate0 = rate.getReceiverUserRate();
                            msMoneyAffirmDto.setReceiverUserRate0(receiverUserRate0);
                            msMoneyAffirmDto.setReceiverUserPrice0(
                                    msMoneyAffirmDto.getOrderCommissionPrice0().multiply(receiverUserRate0).divide(new BigDecimal(100),
                                    2, BigDecimal.ROUND_HALF_UP));
                            // 接单人抽成
                            if (UtilValidate.isNotEmpty(rate.getMerchandiserUserRate())) {
                                BigDecimal merchandiserUserRate0 = rate.getMerchandiserUserRate() ;
                                msMoneyAffirmDto.setMerchandiserUserRate0(merchandiserUserRate0);
                                msMoneyAffirmDto.setMerchandiserUserNo0(rate.getMerchandiserUserNo());
                                msMoneyAffirmDto.setMerchandiserUserName0(rate.getMerchandiserUserName());
                                msMoneyAffirmDto.setMerchandiserUserPrice0(
                                        msMoneyAffirmDto.getOrderCommissionPrice0().multiply(merchandiserUserRate0).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
                            }

                            break;
                        }else{
                            //刚表销售组 会走这个逻辑 刚表销售是直接从订单金额里面抽，不过 抽点很小 10w 接单人才抽2000
                            // 接单人抽成
                            BigDecimal receiverUserRate0 = rate.getReceiverUserRate();
                            msMoneyAffirmDto.setReceiverUserRate0(receiverUserRate0);
                            msMoneyAffirmDto.setReceiverUserPrice0(
                                    msMoneyAffirmDto.getTotalAllPrice().multiply(receiverUserRate0).divide(new BigDecimal(100),
                                            2, BigDecimal.ROUND_HALF_UP));
                            // 接单人抽成
                            if (UtilValidate.isNotEmpty(rate.getMerchandiserUserRate())) {
                                BigDecimal merchandiserUserRate0 = rate.getMerchandiserUserRate();
                                msMoneyAffirmDto.setMerchandiserUserRate0(merchandiserUserRate0);
                                msMoneyAffirmDto.setMerchandiserUserNo0(rate.getMerchandiserUserNo());
                                msMoneyAffirmDto.setMerchandiserUserName0(rate.getMerchandiserUserName());
                                msMoneyAffirmDto.setMerchandiserUserPrice0(
                                        msMoneyAffirmDto.getTotalAllPrice().multiply(merchandiserUserRate0).divide(new BigDecimal(100),
                                                2, BigDecimal.ROUND_HALF_UP));
                            }

                            break;
                        }


                    }



            }


            //介绍人
            if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getIntroduceUserRate())){
                BigDecimal introduceUserPrice = msMoneyAffirmDto.getTotalAllPrice().multiply(msMoneyAffirmDto.getIntroduceUserRate()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                msMoneyAffirmDto.setIntroduceUserPrice(introduceUserPrice);
            }

            if(UtilValidate.isNotEmpty(msMoneyAffirmDto.getType())){
                if("收款确认".equals(msMoneyAffirmDto.getType())){
                    skuNoIn.add(msMoneyAffirmDto.getOrderNo());
                }else{
                    yushouNoIn.add(msMoneyAffirmDto.getOrderNo());
                }
            }

        }
        List<YuShouItem>  dataList=new ArrayList<>();
        if(UtilValidate.isNotEmpty(skuNoIn)){
            FaPiaoItemQueryCriteria criteria1=new FaPiaoItemQueryCriteria();
            criteria1.setSkqrNoIn(skuNoIn);
            List<FaPiaoItem> faPiaoItems = shouKuanQueRenItemList(criteria1);
            if(UtilValidate.isNotEmpty(faPiaoItems)){
                dataList.addAll(faPiaoItems);
            }
        }
        if(UtilValidate.isNotEmpty(yushouNoIn)){
            FaPiaoItemQueryCriteria criteria2=new FaPiaoItemQueryCriteria();
            criteria2.setSkqrNoIn(yushouNoIn);
            List<YuShouItem> faPiaoItems = yushoukuanItemList(criteria2);
            if(UtilValidate.isNotEmpty(faPiaoItems)){
                dataList.addAll(faPiaoItems);
            }
        }
        for (MsMoneyAffirmDto dto : arrs){
            List<YuShouItem> children=new ArrayList<>();
            for (YuShouItem item : dataList){
                if(dto.getOrderNo().equals(item.getSkqrNo())){
                    children.add(item);
                }
            }
            if(UtilValidate.isNotEmpty(children)){
                Map<String,String> saleOrderMap=new HashMap<>();//销售订单号存储map

                for (YuShouItem item : children){
                    if(UtilValidate.isNotEmpty(item.getPiCiHao())){
                        saleOrderMap.put(item.getPiCiHao(),item.getPiCiHao());
                    }else if(UtilValidate.isNotEmpty(item.getXiaoShouDingDanTID())){
                        saleOrderMap.put(item.getXiaoShouDingDanTID(),item.getXiaoShouDingDanTID());
                    }
                }
//                List<String> orderNoList=new ArrayList<>();
                String orderNos=String.join(",",saleOrderMap.keySet());
                dto.setXiaoShouDingDanTID(orderNos);

            }
            dto.setChildren(children);
        }
        return arrs;
    }

    @Override
    public void refetch() {
        initFn();
    }


    @Override
    public TableList<MsMoneyAffirmOrderDto> dklMoneyAffirmPageList(YwMoneyAffirmLogQueryCriteria criteria, YmPageDto ymPage) {
        getPage(ymPage);
        List<MsMoneyAffirmOrderDto> arrs = dklMoneyAffirmList(criteria);
        PageInfo<MsMoneyAffirmOrderDto> pageInfo = new PageInfo<>(arrs);
        TableList<MsMoneyAffirmOrderDto> tableList = new TableList(pageInfo);
        return tableList;
    }

    public List<MsMoneyAffirmOrderDto> dklMoneyAffirmList(YwMoneyAffirmLogQueryCriteria criteria) {
        List<MsMoneyAffirmOrderDto> list = baseMapper.dklMoneyAffirmList(criteria);
        for(MsMoneyAffirmOrderDto orderDto:list){
            if(UtilValidate.isNotEmpty(orderDto.getChildRemark())&&UtilValidate.isNotEmpty(dknMainRat)){
                BigDecimal orderCommissionRate0=null;
                BigDecimal orderCommissionPrice0=null;
                orderDto.setReceiverUserRate0(new BigDecimal(100));//迪卡侬默认没有跟单
                if("Implantation".equals(orderDto.getChildRemark())){//首单
                    orderCommissionRate0=dknMainRat.getNewCustomerRate();
                }
                if("Replenishement".equals(orderDto.getChildRemark())){//翻单
                    orderCommissionRate0=dknMainRat.getOldCustomerOriginalRate();
                }
                if(UtilValidate.isNotEmpty(orderCommissionRate0)){
                    orderCommissionPrice0=orderDto.getTotalAllPrice().multiply(orderCommissionRate0).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal business = orderCommissionPrice0.multiply(orderDto.getBusinessGroupRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    orderDto.setReceiverUserPrice0(business);
                    orderDto.setOrderCommissionRate0(orderCommissionRate0);
                    orderDto.setOrderCommissionPrice0(orderCommissionPrice0);
                    //经理
//                    if(UtilValidate.isNotEmpty(orderDto.getManageUserName0())){
//
//                    }
                    BigDecimal manageUserPrice = orderCommissionPrice0.multiply(orderDto.getManageUserRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                    orderDto.setManageUserPrice0(manageUserPrice);
                    //项目组
                    if(UtilValidate.isNotEmpty(orderDto.getXiangMuGroupName0())){
                        BigDecimal xiangmuGroupPrice = orderCommissionPrice0.multiply(orderDto.getXiangmuGroupRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        orderDto.setXiangMuGroupPrice0(xiangmuGroupPrice);
                    }
                    //基金
                    if(UtilValidate.isNotEmpty(orderDto.getJiJingName0())){
                        BigDecimal jiJingPrice = orderCommissionPrice0.multiply(orderDto.getJiJingRate0()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                        orderDto.setJiJingPrice0(jiJingPrice);
                    }

                }
            }
        }
        return list;
    }


    @Override
    public Long getMaxNum() {
        if (UtilValidate.isNotEmpty(baseMapper.getMaxNum())){
            return baseMapper.getMaxNum();
        }
        return 0l;
    }

    @Override
    public List<FaPiaoItem> shouKuanQueRenItemList(FaPiaoItemQueryCriteria criteria) {
        return baseMapper.shouKuanQueRenItemList(criteria);
    }


    @Override
    public List<FaPiaoItem> shouKuanQueRenItemAllList(FaPiaoItemQueryCriteria2 criteria2) {
        return baseMapper.shouKuanQueRenItemAllList(criteria2);
    }

    @Override
    public List<ExcludeFaPiaoItem> excludeShouKuanQueRenList(FaPiaoItemQueryCriteria criteria) {
        return baseMapper.excludeShouKuanQueRenList(criteria);
    }

    @Override
    public List<YuShouItem> yushoukuanItemList(FaPiaoItemQueryCriteria criteria) {
        return baseMapper.yushoukuanItemList(criteria);
    }

    @Override
    public List<MsMoneyAffirmDto> msChangeAffirmList(YwMoneyAffirmLogQueryCriteria criteria) {
        return baseMapper.msChangeAffirmList(criteria);
    }

    @Override
    public List<MsMoneyAffirmDto> selectChange1List() {
        /**
         * 2024年 1月之后 到 25年 10月 0704 客户 接单人如果为 张鑫 改为曾丽娜
         */
        YwMoneyAffirmLogQueryCriteria criteria=new YwMoneyAffirmLogQueryCriteria();
        criteria.setCustomerNo("0704");
        criteria.setSalesmanName0("张鑫");
        String start_s="2024-01-01 00:00:00";
        String end_s="2025-11-01 00:00:00";
        criteria.setStartTime(start_s);
        criteria.setEndTime(end_s);
        return msChangeAffirmList(criteria);
    }

    @Override
    public void executeSelectChange1() {
        List<MsMoneyAffirmDto> msMoneyAffirmDtos = selectChange1List();
        List<YwMoneyChangeLog> changeLogs=new ArrayList<YwMoneyChangeLog>();
        for(MsMoneyAffirmDto dto:  msMoneyAffirmDtos){

            YwMoneyChangeLog byOrderNo = ywMoneyChangeLogService.getByOrderNo(dto.getOrderNo());
            //确保唯一性
            if(UtilValidate.isEmpty(byOrderNo)){
                YwMoneyChangeLog changeLog=new YwMoneyChangeLog();
                changeLog.setOrderNo(dto.getOrderNo());
                changeLog.setReceiverUserNo("HL004186");
                changeLog.setReceiverUserName("曾丽娜");
                changeLogs.add(changeLog);
            }

        }
        if(UtilValidate.isNotEmpty(changeLogs)){
            ywMoneyChangeLogService.saveOrUpdateBatch(changeLogs);
        }


    }


    @Override
    public void adapterAffirmDtoToAffirmLog(MsMoneyAffirmDto affirmDto, YwMoneyAffirmLog affirmLog) {
        BeanUtils.copyProperties(affirmDto, affirmLog);
        affirmLog.setCurrencyRate(affirmDto.getCurrencyRate());
        affirmLog.setCurrencyType(affirmDto.getCurrencyType());
        affirmLog.setCustomerNo(affirmDto.getCustomerNo());
        affirmLog.setPayTime(affirmDto.getPayTime());
        affirmLog.setTotalAllPrice(affirmDto.getTotalAllPrice());
        affirmLog.setSalesmanName(affirmDto.getSalesmanName0());
        affirmLog.setSalesmanNo(affirmDto.getSalesmanNo0());
        affirmLog.setSalesmanDeptName(affirmDto.getSalesmanDeptName0());
        affirmLog.setSalesmanDeptNo(affirmDto.getSalesmanDeptNo0());
        affirmLog.setManageUserName(affirmDto.getManageUserName0());
        affirmLog.setManageUserNo(affirmDto.getManageUserNo0());
        affirmLog.setManageUserPrice(affirmDto.getManageUserPrice0());
        affirmLog.setXiangMuGroupName(affirmDto.getXiangMuGroupName0());
        affirmLog.setXiangMuGroupPrice(affirmDto.getXiangMuGroupPrice0());
        affirmLog.setOrderNo(affirmDto.getOrderNo());
        affirmLog.setType(affirmDto.getType());
        affirmLog.setOrderCommissionPrice(affirmDto.getOrderCommissionPrice0());
        affirmLog.setOrderCommissionRate(affirmDto.getOrderCommissionRate0());
        affirmLog.setReceiverUserName(affirmDto.getReceiverUserName0());
        affirmLog.setReceiverUserNo(affirmDto.getReceiverUserNo0());
        affirmLog.setReceiverUserRate(affirmDto.getReceiverUserRate0());
        affirmLog.setReceiverUserPrice(affirmDto.getReceiverUserPrice0());
        affirmLog.setMerchandiserUserNo(affirmDto.getMerchandiserUserNo0());
        affirmLog.setMerchandiserUserName(affirmDto.getMerchandiserUserName0());
        affirmLog.setMerchandiserUserRate(affirmDto.getMerchandiserUserRate0());
        affirmLog.setMerchandiserUserPrice(affirmDto.getMerchandiserUserPrice0());
        affirmLog.setJiJingName(affirmDto.getJiJingName0());
        affirmLog.setJiJingPrice(affirmDto.getJiJingPrice0());
    }

    @Override
    public void addExcludeAffirmLog(YwApproveCreateDto dto) {
        List<MsMoneyAffirmDto> list = dto.getList();
        String userId = getUserId();
        String userName = getUserName();
        List<YwMoneyAffirmLog> addList = new ArrayList<>();
        for(MsMoneyAffirmDto affirmDto:list){
            YwMoneyAffirmLog affirmLog = new YwMoneyAffirmLog();
            adapterAffirmDtoToAffirmLog(affirmDto,affirmLog);
            affirmLog.setApproveNo("排除");
            affirmLog.setUserId(userId);
            affirmLog.setUserName(userName);
            addList.add(affirmLog);
        }
        saveOrUpdateBatch(addList);
    }



    @Override
    public List<YwMoneyAffirmLog> getExcludeAffirmList(String types) {
        YwMoneyAffirmLogQueryCriteria criteria=new YwMoneyAffirmLogQueryCriteria();
        criteria.setApproveNo("排除");
        String[] split = types.split(",");
        criteria.setTypeIn(Arrays.asList(split));
        String userId = getUserId();
        criteria.setUserId(userId);
        List<YwMoneyAffirmLog> ywMoneyAffirmLogs = queryAll(criteria);
        return ywMoneyAffirmLogs;
    }

    /**
     * 查看 已抽成 表格
     * @param criteria
     * @return
     */
    @Override
    public TableList<YwMoneyAffirmLog> tablePassAffirmList(YwMoneyAffirmLogQueryCriteria criteria, YmPageDto ymPage) {
        getPage(ymPage);
        String userId = getUserId();
        criteria.setUserId(userId);
        List<YwMoneyAffirmLog> arrs = getPassAffirmList(criteria);
        PageInfo<YwMoneyAffirmLog> pageInfo = new PageInfo<>(arrs);
        TableList<YwMoneyAffirmLog> tableList = new TableList(pageInfo);
        return tableList;
    }

    /**
     * 查看 已抽成
     * @param criteria
     * @return
     */
    @Override
    public List<YwMoneyAffirmLog> getPassAffirmList(YwMoneyAffirmLogQueryCriteria criteria) {
        return baseMapper.getPassAffirmList(criteria);
    }

    @Override
    public void removeExcludeAffirmLog(String id) {
        removeById(id);
    }


    @Override
    public CountMoneyAffirmDto getCountDeptTotalLog(String month) {
        CountMoneyAffirmDto countMoneyAffirmDto = null;

        String userName = getUserName();
        DEmployee userInfo = ywUserService.getUserInfoToSlave2(userName);
        if(UtilValidate.isEmpty(userInfo)){
            return countMoneyAffirmDto;
        }
        //部门编号
        String dtid = userInfo.getDtid();
        List<String> salesmanDeptNos=new ArrayList<>();

        boolean isWatche=false;//是否表部  迪卡侬，OEM营销部
        /**
         * HL02-2  迪卡侬
         * HL02-3  OEM营销部
         */
        List<String> salesmanDeptList=new ArrayList<>();
        if(dtid.equals("HL02-2")||dtid.equals("HL02-3")){
            salesmanDeptNos.add("HL02-2");
            DDepartment dept1 = dDepartmentService.getByDeptNo("HL02-2");
            salesmanDeptList.add(dept1.getName());
            salesmanDeptNos.add("HL02-3");
            DDepartment dept2 = dDepartmentService.getByDeptNo("HL02-3");
            salesmanDeptList.add(dept2.getName());
            isWatche=true;
        }
       // salesmanDeptNos.add(dtid);
        YwMoneyAffirmLogCountQueryCriteria criteria=new YwMoneyAffirmLogCountQueryCriteria();
        criteria.setSalesmanDeptNoIn(salesmanDeptNos);
        criteria.setMonth(month);
        if(isWatche){
            DynamicDataSourceContextHolder.push("slave2");
        }
        return countMoneyAffirmDto;
    }


    @Override
    public List<CountMoneyUserDto> getCountDeptTotalLog_biao(YwMoneyAffirmLogCountQueryCriteria criteria) {

        List<CountMoneyUserDto> countMoneyUserDtos = baseMapper.countDeptTotalLog(criteria);

        //判断是否钟部 HL02-1
        if(UtilValidate.isNotEmpty(criteria.getSalesmanDeptNoIn())&&criteria.getSalesmanDeptNoIn().get(0).equals("HL02-1")){
            boolean isMange=false;
            for(CountMoneyUserDto countMoneyUserDto:countMoneyUserDtos){
                if(countMoneyUserDto.getUserType().equals("manage_user")){
                    isMange=true;
                }
            }
            //没有经理的提成再来重新计算
            if(!isMange){
                YwDeptQueryCriteria c2=new YwDeptQueryCriteria();
                c2.setDeptName("钟营销部");
                List<YwDept> ywDepts = ywDeptService.queryAll(c2);
                if(UtilValidate.isNotEmpty(ywDepts)){
                    YwDept ywDept = ywDepts.get(0);
                    YwCommissionConfigQueryCriteria c3=new YwCommissionConfigQueryCriteria();
                    c3.setKeyword(ywDept.getDeptName());
                    List<YwCommissionConfig> ywCommissionConfigs = ywCommissionConfigService.queryAll(c3);
                    if(UtilValidate.isNotEmpty(ywCommissionConfigs)){
                        YwCommissionConfig ywCommissionConfig = ywCommissionConfigs.get(0);

                        BigDecimal manageUserRate = ywCommissionConfig.getManageUserRate();
                        BigDecimal totalAll = baseMapper.sumDeptAllPrice(criteria);
                        if(UtilValidate.isNotEmpty(totalAll)){
                            BigDecimal divide = totalAll.multiply(new BigDecimal(0.1)).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            CountMoneyUserDto countMoneyUserDto = new CountMoneyUserDto();
                            countMoneyUserDto.setUserName("许建晶");
                            countMoneyUserDto.setUserPrice(divide);
                            countMoneyUserDto.setUserType("manage_user");
                            countMoneyUserDto.setNote("收款人民币总金额*0.1%");
                            countMoneyUserDtos.add(countMoneyUserDto);
                        }
                    }
                }
            }
        }
        return countMoneyUserDtos;
    }

    @Override
    public List<CountMoneyUserDto> countApproverNoTotal(YwMoneyAffirmLogCountQueryCriteria criteria) {
        List<CountMoneyUserDto> countMoneyUserDtos = baseMapper.countApproverNoTotal(criteria);

        DbApprovalLog approvalLog = dbApprovalLogService.getApproveNo(criteria.getApproverNo());
        //汇总 钟部经理抽成
        if(UtilValidate.isNotEmpty(approvalLog)){
            String user_names="许建晶，manage，张爱君，庄嫚艺，许毅坚，戴燕云，邵琪";
            String userName = getUserName();
            if(user_names.contains(userName)){
                YwDeptQueryCriteria c2=new YwDeptQueryCriteria();
                c2.setDeptName("钟营销部");
                List<YwDept> ywDepts = ywDeptService.queryAll(c2);
                if(UtilValidate.isNotEmpty(ywDepts)){
                    YwDept ywDept = ywDepts.get(0);
                    YwCommissionConfigQueryCriteria c3=new YwCommissionConfigQueryCriteria();
                    c3.setKeyword(ywDept.getDeptName());
                    List<YwCommissionConfig> ywCommissionConfigs = ywCommissionConfigService.queryAll(c3);
                    if(UtilValidate.isNotEmpty(ywCommissionConfigs)){
                        YwCommissionConfig ywCommissionConfig = ywCommissionConfigs.get(0);

                        BigDecimal manageUserRate = ywCommissionConfig.getManageUserRate();

                        //钟部的业务员 们 不是经理的 不能看到
//                        boolean b = showZhongBuTotal(ywDept);
                        DynamicDataSourceContextHolder.clear();
                        DynamicDataSourceContextHolder.push("slave2");
                        YwMoneyAffirmLogQueryCriteria c4=new YwMoneyAffirmLogQueryCriteria();
                        c4.setApproveNo(approvalLog.getApproveNo());
                        c4.setSalesmanDeptName0Like("钟营销部");
                        BigDecimal totalAll = baseMapper.sumApproverNo(c4);
                        if(UtilValidate.isNotEmpty(totalAll)
                                &&totalAll.compareTo(BigDecimal.ZERO)>0){
                            BigDecimal divide = totalAll.multiply(new BigDecimal(0.1)).divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
                            CountMoneyUserDto countMoneyUserDto = new CountMoneyUserDto();
                            countMoneyUserDto.setUserName("许建晶");
                            countMoneyUserDto.setUserPrice(divide);
                            countMoneyUserDto.setUserType("manage_user");
                            countMoneyUserDto.setNote("收款人民币总金额*0.1%");
                            countMoneyUserDtos.add(countMoneyUserDto);
                        }
                    }
                }
            }

        }
        return countMoneyUserDtos;
    }


    public boolean showZhongBuTotal(YwDept dept){
        boolean show=true;
        String userName = getUserName();
        DEmployee userInfoToSlave2 = ywUserService.getUserInfoToSlave2(userName);
        if(UtilValidate.isNotEmpty(userInfoToSlave2)){
            if(userInfoToSlave2.getDname().equals(dept.getDeptName())
                    &&!userInfoToSlave2.getName().equals(dept.getManageUserName())){
                show=false;
            }
        }
        return show;
    }


    @Override
    public List<QiChuItem> qiChuItemList(QiChuQueryCriteria criteria) {
        return baseMapper.qiChuItemList(criteria);
    }

    @Override
    public QiChuItem qiChuItemOne(QiChuQueryCriteria criteria) {
        return baseMapper.qiChuItemOne(criteria);
    }
}
